package cn.push.embed.core.socket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;


public class NioSocketReceiveThread implements Runnable {
	private Selector selector;  
	private NioSocketConnection nioSocketConnection;
	private NioSocket.ConnectionHandler nsHandler;
    public NioSocketReceiveThread(NioSocketConnection nioSocketConnection) {
    	this.nioSocketConnection=nioSocketConnection;
    	this.nsHandler=this.nioSocketConnection.getNsHandler();
        this.selector = this.nioSocketConnection.getSelector();  
        new Thread(this).start();  
    }  
    @SuppressWarnings("static-access")  
    public void run() {  
        try {  
            while (selector!=null) {
                if (selector.select() < 1){
                    return;
                }

                for (SelectionKey sk : selector.selectedKeys()) {  
                    if (sk.isReadable()) {  
                        SocketChannel sc = (SocketChannel) sk.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        int lenth=sc.read(buffer);
                        if(lenth>0){
	                        buffer.flip();
	                        byte[] bytes=new byte[lenth];
	                        buffer.get(bytes, 0, lenth);
	                       nsHandler.onBinaryMessage(bytes);
	                        sk.interestOps(SelectionKey.OP_READ); 
                        }
                    }  
                   selector.selectedKeys().remove(sk);  
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }  
        } catch (Exception ex) {
        	nioSocketConnection.setmActive(false);
        	nioSocketConnection.disConnect();
        	nsHandler.onClose(NioSocket.ConnectionHandler.CLOSE_CONNECTION_LOST, "A previously established connection was lost unexpected");
            ex.printStackTrace();  
            return;
        }  
    }  

}
